<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>富扬数据看板</title>
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  <link rel="stylesheet" href="/stylesheets/css/bootstrap.min.css">
  <link rel="stylesheet" href="/stylesheets/css/select2.min.css">
  <link rel="stylesheet" href="/stylesheets/css/dataTables.bootstrap.min.css">
  <link rel="stylesheet" href="/stylesheets/css/AdminLTE.min.css">
  <link rel="stylesheet" href="/stylesheets/skins/_all-skins.min.css">
  <style>
    .alert{
      padding: 8px;
      position: fixed;
      z-index: 2000;
      width: 300px;
      top: 30px;
      left:0; right:0;
      margin: 0 auto;
    }
    .alert p{
      text-align: center;
      font-size: 14px;
    }
    .close{
      font-size: 16px;
    }
    .delete, .update{
      cursor: pointer;
    }
    .deleteUser{
      margin-right: 10px;
    }
    a:hover{
      text-decoration: underline;
    }
    #example button{
      text-decoration: underline;
    }
    #example button, #example a{
      border: none;
      background: none;
    }
    #example button span{
      font-weight: normal;
      font-size: 12px;
      color: #4d9ecc;
      text-decoration: underline;
    }
    #example a:hover{
      cursor: pointer;
    }
    .content-header>h1>.breadcrumb {
      background: transparent;
      margin-top: 0;
      margin-bottom: 0;
      font-size: 12px;
      padding: 7px 5px;
      border-radius: 2px;
      display: inline-block;
    }
  </style>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">

  <%- include("./public/header.ejs") %>

  <%- include("./public/aside.ejs") %>

  <div id="alert"></div>

  <div class="content-wrapper">
    <section class="content-header">
      <h1>
        人员管理
        <ol class="breadcrumb">
          <li><a href="/"><i class="glyphicon glyphicon-dashboard"></i>首页</a></li>
          <li class="active">人员管理</li>
        </ol>
      </h1>
    </section>
    <section class="content">
      <div class="row">
        <div class="col-md-12">
          <div class="box">
            <div class="box-header">
              <h3 class="box-title">
                <a class="btn btn-info btn-xs" data-toggle="modal" data-target="#modal-user">添加人员</a>
              </h3>
            </div>
            <div class="box-body">
              <table id="example" class="table table-bordered table-condensed table-striped table-hover">
                <thead>
                  <tr>
                    <th style="width: 100px;">姓名</th>
                    <th style="width: 400px;">部门</th>
                    <th style="width: 200px;">职务</th>
                    <th style="width: 100px;">密码</th>
                    <th style="width: 120px;">操作</th>
                  </tr>
                </thead>
                <tbody>
                  <% for(let i=0;i<userData.length;i++){ %>
                    <tr>
                      <td><%= userData[i].employeesName %></td>
                      <td>
                        <%= userData[i].team?.map(v=>v.tName).join(", ") %>
                        <span class="btn btn-info btn-xs update-team" data-toggle="modal" data-target="#modal-team" data-uid="<%= userData[i].uId %>" style="width: 40px;margin-left: 20px;">修改</span>
                      </td>
                      <td>
                        <%- userData[i].job?.jName || '<span>请选择</span>' %>
                        <span class="btn btn-info btn-xs update-job" data-toggle="modal" data-target="#modal-job"  data-uid="<%= userData[i].uId %>" style="width: 40px;margin-left: 20px;">修改</span>
                      </td>
                      <td><a class="updatePassword update" data-href="/user/password?uId=<%= userData[i].uId %>">******</a></td>
                      <td>
                        <a class="deleteUser delete" data-href="/user/deleteUser?uId=<%= userData[i].uId %>">删除</a>
                        <a class="update" href="/user/power?uId=<%= userData[i].uId %>">权限</a>
                      </td>
                    </tr>
                  <% } %>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>

  <%- include("./public/footer.ejs") %>
</div>

<!-- 添加用户 -->
<div class="modal fade" id="modal-user">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <form role="form" method="post" action="/user/add">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title">请输入用户信息</h4>
        </div>
        <div class="modal-body">
          <input type="text" class="form-control" placeholder="姓名" name="employeesName" required autocomplete="off">
          <select class="form-control addTeam" style="width: 100%;" name="team"></select>
          <select class="form-control addJob" style="width: 100%;" name="job"></select>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default pull-left" data-dismiss="modal">关闭</button>
          <button type="submit" class="btn btn-primary">提交</button>
        </div>
      </form>
    </div>
  </div>
</div>
<!-- 修改部门 -->
<div class="modal fade" id="modal-team">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">请选择部门</h4>
      </div>
      <div class="modal-body">
        <select class="form-control team" style="width: 100%;height: 36px;" multiple></select>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default pull-left" data-dismiss="modal">关闭</button>
        <button type="submit" class="btn btn-primary submit-team" data-dismiss="modal">提交</button>
      </div>
    </div>
  </div>
</div>
<!-- 修改职位 -->
<div class="modal fade" id="modal-job">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">请选择职位</h4>
      </div>
      <div class="modal-body">
        <select class="form-control job" style="width: 100%;" placeholder="Job"></select>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default pull-left" data-dismiss="modal">关闭</button>
        <button type="submit" class="btn btn-primary submit-job" data-dismiss="modal">提交</button>
      </div>
    </div>
  </div>
</div>

<script src="/javascripts/jquery.min.js"></script>
<script src="/javascripts/bootstrap.min.js"></script>
<script src="/javascripts/jquery.dataTables.min.js"></script>
<script src="/javascripts/dataTables.bootstrap.min.js"></script>
<script src="/javascripts/select2.full.min.js"></script>
<script src="/javascripts/adminlte.min.js"></script>
<script>

  const userData = <%- JSON.stringify(userData) %>;
  const teamData = <%- JSON.stringify(teamData) %>;
  const jobData = <%- JSON.stringify(jobData) %>;

  const table = $('#example').DataTable({
    'searching': true,
    "ordering": true,
    "pageLength": 100,
    language: {
      "sProcessing": "处理中...",
      "sLengthMenu": "显示 _MENU_ 项结果",
      "sZeroRecords": "没有匹配结果",
      "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
      "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
      "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
      "sInfoPostFix": "",
      "sSearch": "搜索:",
      "sUrl": "",
      "sEmptyTable": "表中数据为空",
      "sLoadingRecords": "载入中...",
      "sInfoThousands": ",",
      "oPaginate": {
          "sFirst": "首页",
          "sPrevious": "上页",
          "sNext": "下页",
          "sLast": "末页"
      },
      "oAria": {
          "sSortAscending": ": 以升序排列此列",
          "sSortDescending": ": 以降序排列此列"
      }
    }
  })

  let uId = '';
  $('#example').on("click", ".update-team", function(){
    uId = this.dataset.uid;
    $('.team').val(()=>{
      return userData.find(v=>v.uId===uId).team.map(v=>v.tId);
    }).trigger("change");
  })

  $('#example').on("click", ".update-job", function(){
    uId = this.dataset.uid;
    $('.job').val(()=>{
      return userData.find(v=>v.uId===uId).job.jId;
    }).trigger("change");
  })

  let nowTeam = [];
  $('.team').select2({
    minimumResultsForSearch: -1,
    allowClear: true,
    placeholder: '请选择部门',
    data: teamData.map(val=>({
      id: val.tId,
      text: val.tName
    }))
  }).on('change', function(e){
    nowTeam = $(this).val()
  });

  $(".submit-team").click(function(e){
    $.ajax({
      url: '/user/set',
      method: 'post',
      data: {
        uId: uId,
        tId: JSON.stringify(nowTeam)
      }
    }).then(res=>{
      alert({type:'success', msg:'操作成功', close:()=>{
        location.reload();
      }})
    }).catch(code=>{
      console.error( code );
      alert({type:'danger', msg:JSON.stringify(code)})
    })
  })

  // 职位
  let job = '';
  $('.job').select2({
    minimumResultsForSearch: -1,
    placeholder: '请选择职务',
    data: jobData.map(v=>({
      id: v.jId,
      text: v.jName
    }))
  }).on('change', function(e){
    job = $(this).val()
  });
  $(".submit-job").on("click", function(){
    $.ajax({
      url: '/user/set',
      method: 'post',
      data: {
        uId: uId,
        jId: job
      }
    }).then(res=>{
      alert({type:'success', msg:'操作成功', close:()=>{
        location.reload();
      }})
    }).catch(code=>{
      console.error( code );
      alert({type:'danger', msg:JSON.stringify(code)})
    })
  })

  // 删除用户
  $('.deleteUser').click(function(){
    if(confirm("确认删除该员工信息？")){
      location.href = this.dataset.href;
    }
  })

  // 重置密码
  $(".updatePassword").click(function(){
    if(confirm("该用户密码将被重置为手机号 后6位 ，是否重置密码？")){
      location.href = this.dataset.href;
    }
  })

  // 添加用户-部门
  $('.addTeam').select2({
    minimumResultsForSearch: -1,
    allowClear: true,
    placeholder: '请选择部门',
    data: [{
      id:'', text:''
    }, ...teamData.map(val=>({
      id: val.tId,
      text: val.tName
    }))]
  })
  // 添加用户-职位
  $('.addJob').select2({
    minimumResultsForSearch: -1,
    allowClear: true,
    placeholder: '请选择职位',
    data: [{
      id:'', text:''
    }, ...jobData.map(val=>({
      id: val.jId,
      text: val.jName
    }))]
  })

  function alert(ops){
    const {type='info', msg='提示信息', close} = ops;
    const innerHTML = `<div class="alert alert-${type}"><span class="close" data-dismiss="alert" aria-hidden="true">&times;</span><p>${msg}!</p></div>`;
    if($("#alert").html()){
      $("#alert").show(100);
    }else{
      $("#alert").html(innerHTML);
    }

    clearTimeout($("#alert").t);
    $("#alert").t = setTimeout(()=>{
      $("#alert").hide(100, close);
    }, 1000)
    return $("#alert");
  }
</script>
</body>
</html>
